<?php
/**
 * Created by PhpStorm.
 * User: shaowei
 * Date: 2018/12/21
 * Time: 上午11:44
 */

namespace App\Http\Services;

use App\Http\Model\Help;
use App\Http\Model\Hint;
use App\Http\Model\Room;
use App\Http\Model\System;
use App\Http\Model\User;
use App\Http\Model\UserRegisterLog;
use App\Lib\oss;
use App\Lib\SecurityCode;
use Illuminate\Support\Facades\Redis;
use Ramsey\Uuid\Uuid;
// use App\Lib\Shumei;
use App\Http\Model\Mood;
use App\Http\Model\AliVerify;
use App\Http\Model\UserBlacklist;

//use AopClient;
//use ZhimaCustomerCertificationCertifyRequest;
//use ZhimaCustomerCertificationMaterialCertifyRequest;
//use ZhimaCustomerCertificationInitializeRequest;

class SystemServices extends CommonServices
{
    private $model_system;
    private $model_user;
    private $mood_model;
    private $mime_map = [
        "png" => "image",
        "jpeg" => "image",
        "webp" => "image",
        "bmp" => "image",
        "gif" => "image",
        "jpg" => "image",
        "3gp" => "video",
        "3gpp" => "video",
        "3gpp2" => "video",
        "avi" => "video",
        "mp4" => "video",
        "quicktime" => "video",
        "mpeg" => "video",
        "webm" => "video",
        "mp2ts" => "video",
        "mov" => "video",
        "amr" => "audio",
        "aac" => "audio",
        "mp3" => "audio",
        "m4a" => "audio",
        "log" => "log"

    ];

    protected $pushCheckHour = 'PUSH:CHECK:%s';

    protected $helpModel;
    protected $securityCode;
    protected $model_room;
    protected $model_user_register;
    protected $aliVerifyModel;
    protected $userBlacklistModel;

    private $aop = null;    // AopClient 实例化对象

    public function __construct()
    {
        $this->model_system = new System;
        $this->model_user = new User;
        $this->helpModel = new Help();
        $this->securityCode = new SecurityCode();
        $this->model_room = new Room();
        $this->model_user_register = new UserRegisterLog();
        $this->mood_model = new Mood();
        $this->aliVerifyModel = new AliVerify();
        $this->userBlacklistModel = new UserBlacklist();

    }

    public function get_last_version($platform_id, $channel_id){
        $ua = $this->parse_app_UA();
        if ($channel_id == 1){
            $channel_id = $ua['channel_id'];
        }
        return $this->model_system->get_last_version($platform_id, $channel_id);
    }


    public function get_expression_last_version(){
        return $this->model_system->get_expression_last_version();
    }

    public function get_expression_new_last_version(){
        return $this->model_system->get_expression_new_last_version();
    }

    /**
     * 可选心情列表
     * */
    public function moodList()
    {
        $list = $this->mood_model->getAll();

        return ["list"=>$list];
    }


    /**
     * 上传资源
     * @param $type 1 相册 2 反馈 3 房间 4 动态 5 广告 6 礼物 7 商场 8 app升级 9 勋章 10 页面  13 公会头像 14 单聊天音频 15共享音乐 16家族头像
     * @param $exts 扩展名 "png,jpeg"
     * @return array|null
     * @throws \Exception
     */
    public function get_put_file_url($type, $exts){
        header('Access-Control-Allow-Origin:*');
        $osshelper = new oss();
        $current_user = $this->model_user->get_current_user();
        if (empty($current_user)){
            $user_id = 'platform';
        }else
        {
            $user_id = $current_user['user_id'];
        }

        $str_type = 'null';
        if($type == 1){
            $str_type = "album";
        }
        if($type == 2){
            $str_type = "report";
        }
        if($type == 3){
            $str_type = "room";
        }
        if($type == 4){
            $str_type = "trends";
        }
        if($type == 5){
            $str_type = "ad";
        }
        if($type == 6){
            $str_type = "gift";
        }
        if($type == 7){
            $str_type = "mall";
        }
        if($type == 8){
            $str_type = "app";
        }
        if($type == 9){
            $str_type = "medal";
        }
        if($type == 10){
            $str_type = "template";
        }
        if($type == 11){
            $str_type = "meet";
        }
        if($type == 13){
            $str_type = 'union';
        }
        if($type == 14) {
            $str_type = 'chatVoice';
        }
        if($type ==15){
            $str_type = 'shareMusic';
        }
        if($type ==16){
            $str_type = 'family';
        }
        if($type ==17){

        }

        if($type ==18){
        }

        if($type == 19) {
            $str_type = 'pc'; // pc端上传
        }

        if ($type == 20) {

        }

        if ($type == 21) {
            $str_type = 'room_background';//背景墙
        }
        if ($type == 22) {
            $str_type = 'agora';//声网
        }
        if ($type == 23) {
            $str_type = 'mate';//缘分配对
        }
        if($type == 24){
            $str_type = 'files';//文件类型
        }
        if ($type == 25) {
            $str_type = 'identity';//主播
        }
        if ($type == 26) {
            $str_type = 'settle';//结算
        }
        if ($type == 27) {
            $str_type = 'equip/img';//装备
        }
        if ($type == 28) {
            $str_type = 'video';//视频类型
        }
        if($type == 29){
            $str_type = 'nameplate';
        }

        $ret_data = [];
        $pic_domain = getPicDomain() . '/';
        $ext_arr = explode(',', $exts);
        $count = count($ext_arr);
        for ($i = 0; $i < $count; $i++){
            if (empty($ext_arr[$i])) {
                continue;
            }
            $mime = 'none';
            $ext = strtolower($ext_arr[$i]);
            if (isset($this->mime_map[$ext])){
                $mime = $this->mime_map[$ext];
            }
            $uri = $str_type. '/' . $mime . '/' . strval($user_id) . '/' . Uuid::uuid1() . '.' . $ext;
            $item = ["url"=>$pic_domain . $uri, "uri"=> $uri];
            $item['put_url'] = $osshelper->get_object_put_url($uri);
            array_push($ret_data, $item);

        }
        return $ret_data;
    }


    public function get_config(){
        return $this->model_system->get_config();
    }

    public function get_audit_switch($version_id,$platform_id,$channel_id){
        return $this->model_system->get_audit_switch($version_id,$platform_id,$channel_id);
    }

    /**
     * 清除缓存
     * @param $type
     */
    public function clear_cache($type){
        $this->model_system->clear_cache($type);
    }

    /**
     * 根据获取版本数据
     * */
    public function getSystemVersion()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            $this->I('channel_id', '渠道ID', 'int', true, '渠道ID不能为空');

            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
            extract($variables); //数组参数化

            $ret = $this->model_system->getSystemVersion($this->requestData);
            if (empty($ret)) {
                $code = Hint::ERR_DATA_NOT_EXIST;
                $msg = '版本' . Hint::getErrCodeMsg($code);
                break;
            }

            $data = $ret;

            header("location:".$ret['download_url']);

        } while (false);

        return compact('code', 'msg', 'data');
    }

    ################# 统一图形验证码模块 ##########################################

    /**
     * 获取图形验证码
     * */
    public function captchaCode()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            $this->I('phone', '手机号', 'string', false);

            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
            extract($variables); //数组参数化

            // 判断手机号不存在时获取当前登录用户手机号
            if (!isset($this->requestData['phone']) or empty($this->requestData['phone'])) {

                // 查询当前登录用户数据
                $currUser = $this->model_user->get_current_user();
                if (empty($currUser) or empty($currUser['phone'])) {
                    $code = Hint::ERR_PARAMS_CHECK_FAIL;
                    $msg = Hint::getErrCodeMsg($code);
                    break;
                }

                $this->requestData['phone'] = $currUser['phone'];
            }

            // 限制生成图形验证码60秒内10次
            if (!redis_num_lock('CACHE:GENERATE:CAPTCHA_CODE:' . $this->requestData['phone'], 60, 10)) {
                $code = Hint::NOT_ALLOW_SEND_CODE;
                $msg = Hint::getErrCodeMsg($code);
                break;
            }

            // 生成验证码
            $generateCaptchaCode = $this->securityCode->generateCaptchaCode();

            // 手机号对应的图形验证码 180秒
            $this->model_system->storeCaptchaCode($this->requestData['phone'], $generateCaptchaCode);

            // 输出图形验证码
            $data['stream_type'] = 'gif';
            $data['stream_data'] = base64_encode($this->securityCode->index());

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 校验图形验证码
     * */
    public function checkCaptchaCode()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            $this->I('phone', '手机号', 'string', false);
            $this->I('captcha_code', '图形验证码', 'string', true, '验证码不能为空');
            // $this->I('is_delete_code_state', '是否删除验证码状态', 'int', false);// 0=不删除验证码 1=删除验证码

            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
            extract($variables); //数组参数化

            if (strlen($this->requestData['captcha_code']) != 4) {
                $code = Hint::CHECK_CAPTCHA_CODE_ERROR;
                $msg = Hint::getErrCodeMsg($code);
                break;
            }

            // 判断手机号不存在时获取当前登录用户手机号
            if (!isset($this->requestData['phone']) or empty($this->requestData['phone'])) {

                // 查询当前登录用户数据
                $currUser = $this->model_user->get_current_user();
                if (empty($currUser) or empty($currUser['phone'])) {
                    $code = Hint::ERR_PARAMS_CHECK_FAIL;
                    $msg = Hint::getErrCodeMsg($code);
                    break;
                }

                $this->requestData['phone'] = $currUser['phone'];
            }

            $checkCaptchaCode = $this->model_system->checkCaptchaCode($this->requestData['phone'], $this->requestData['captcha_code'], 1);
            if (!$checkCaptchaCode) {
                $code = Hint::CHECK_CAPTCHA_CODE_ERROR;
                $msg = Hint::getErrCodeMsg($code);
                break;
            }

            $data['phone'] = $this->requestData['phone'];

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 记录操作手机号时间
     * */
    public function recordPhoneOpTime()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            $this->I('phone', '手机号', 'string', false);

            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
            extract($variables); //数组参数化

            // 判断手机号不存在时获取当前登录用户手机号
            if (!isset($this->requestData['phone']) or empty($this->requestData['phone'])) {

                // 查询当前登录用户数据
                $currUser = $this->model_user->get_current_user();
                if (empty($currUser) or empty($currUser['phone'])) {
                    $code = Hint::ERR_PARAMS_CHECK_FAIL;
                    $msg = Hint::getErrCodeMsg($code);
                    break;
                }

                $this->requestData['phone'] = $currUser['phone'];
            }

            $this->model_system->recordPhoneOpTime($this->requestData['phone']);

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 检验是否存在手机号操作时间
     * */
    public function checkRecordPhoneOpTime()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            $this->I('phone', '手机号', 'string', false);

            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
            extract($variables); //数组参数化

            // 判断手机号不存在时获取当前登录用户手机号
            if (!isset($this->requestData['phone']) or empty($this->requestData['phone'])) {

                // 查询当前登录用户数据
                $currUser = $this->model_user->get_current_user();
                if (empty($currUser) or empty($currUser['phone'])) {
                    $code = Hint::ERR_PARAMS_CHECK_FAIL;
                    $msg = Hint::getErrCodeMsg($code);
                    break;
                }

                $this->requestData['phone'] = $currUser['phone'];
            }

            $checkRecordPhoneOpTime = $this->model_system->checkRecordPhoneOpTime($this->requestData['phone']);
            if (!$checkRecordPhoneOpTime) {
                $code = Hint::NEED_CAPTCHA_CODE;
                $msg = Hint::getErrCodeMsg($code);
                break;
            }

        } while (false);

        return compact('code', 'msg', 'data');
    }

    ################# 后台调用 ##########################################

    /**
     * 系统配置创建
     * */
    public function configCreate()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            try {
                $this->I('key', '键', 'string', true, '键不能为空');
                $this->I('value', '值', 'string', false, '');
                $this->I('desc', '描述', 'string', true, '描述不能为空');
                $this->I('type', '字段类型', 'int', false, '字段类型不能为空');// 0:string(字符串) 1:int(整形)
                $this->I('category', '分类', 'string', false, '分类不能为空');// 0:string(字符串) 1:int(整形)

                $variables = [];
                $checkParams = $this->check($this->requestData, $variables); //校验数据
                extract($checkParams);
                if ($code !== Hint::SUCCESS) {
                    break;
                }
                extract($variables); //数组参数化

                $data['id'] = $this->model_system->insertSingle($this->requestData);
                $this->model_system->clearSystemConfigCache();//清除缓存
                if ($data['id'] <= 0) {
                    $code = Hint::ERR_DATA_CREATE_FAIL;
                    $msg = '系统配置' . Hint::getErrCodeMsg($code);
                    break;
                }

                //配置更新后，需要处理的业务逻辑放到这里
                $this->handleSystemConfigLogic($this->requestData['key'], $this->requestData['value']);

            } catch (\Exception $e) {
                $code = Hint::ERR_SYS_FAIL;
                $msg = 'message：' . $e->getMessage() . '，line：' . $e->getLine();
                break;
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 系统配置更新
     * */
    public function configUpdate()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            try {
                $this->I('id', '系统配置ID', 'int', true, '系统配置ID不能为空');
                $this->I('key', '键', 'string', false, '键不能为空');
                $this->I('value', '值', 'string', false, '值不能为空');
                $this->I('desc', '描述', 'string', false, '描述不能为空');
                $this->I('type', '字段类型', 'int', false, '字段类型不能为空');// 0:string(字符串) 1:int(整形)
                $this->I('category', '分类', 'string', false, '分类不能为空');// 0:string(字符串) 1:int(整形)

                $variables = [];
                $checkParams = $this->check($this->requestData, $variables); //校验数据
                write_log('qzz','qzz',$checkParams);
                extract($checkParams);
                if ($code !== Hint::SUCCESS) {
                    break;
                }
                extract($variables); //数组参数化

                $id = $this->requestData['id'];
                // 移除请求数据中的ID
                unset($this->requestData['id']);

                if (empty($this->requestData)) {
                    $code = Hint::ERR_PARAMS_CHECK_FAIL;
                    $msg = Hint::getErrCodeMsg($code) . ':至少包含任意一个业务参数';
                    break;
                }

                $this->model_system->singleUpdate(['id' => $id], $this->requestData);
                $this->model_system->clearSystemConfigCache();//清除缓存
                $data['id'] = intval($id);

                //配置更新后，需要处理的业务逻辑放到这里
                $this->handleSystemConfigLogic($this->requestData['key'], $this->requestData['value']);

            } catch (\Exception $e) {
                $code = Hint::ERR_SYS_FAIL;
                $msg = 'message：' . $e->getMessage() . '，line：' . $e->getLine();
                break;
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 系统配置删除
     * */
    public function configRemove()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            try {
                $this->I('id', '系统配置ID', 'int', true, '系统配置ID不能为空');

                $variables = [];
                $checkParams = $this->check($this->requestData, $variables); //校验数据
                extract($checkParams);
                if ($code !== Hint::SUCCESS) {
                    break;
                }
                extract($variables); //数组参数化

                $query = $this->model_system::query()->where('id', $this->requestData['id'])->first();
                $ret = $this->model_system->singleRemove($this->requestData);
                if (!$ret) {
                    $code = Hint::ERR_DATA_REMOVE_FAIL;
                    $msg = '系统配置' . Hint::getErrCodeMsg($code);
                    break;
                }

            } catch (\Exception $e) {
                $code = Hint::ERR_SYS_FAIL;
                $msg = 'message：' . $e->getMessage() . '，line：' . $e->getLine();
                break;
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 版本创建
     * */
    public function versionCreate()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            try {
                $this->I('version_id', '版本号', 'string', true, '版本号不能为空');
                $this->I('platform_id', '平台', 'int', true, '平台不能为空');//  1:IOS 2:Android
                $this->I('upgrade_type', '升级类型', 'int', true, '升级类型不能为空');// 0.不升级 1. 强制升级 2.普通升级
                $this->I('channel_id', '渠道ID', 'int', true, '渠道ID不能为空');
                $this->I('download_url', '下载链接', 'string', true, '下载链接不能为空');
                $this->I('describe', '版本说明', 'string', true, '版本说明不能为空');
                $this->I('audit_switch', '开关', 'int', false);// 0:关闭 1:开启

                $variables = [];
                $checkParams = $this->check($this->requestData, $variables); //校验数据
                extract($checkParams);
                if ($code !== Hint::SUCCESS) {
                    break;
                }
                extract($variables); //数组参数化

                $this->model_system->table = 'system_version';
                $data['id'] = $this->model_system->insertSingle($this->requestData);
                if ($data['id'] <= 0) {
                    $code = Hint::ERR_DATA_CREATE_FAIL;
                    $msg = '版本' . Hint::getErrCodeMsg($code);
                    break;
                }

            } catch (\Exception $e) {
                $code = Hint::ERR_SYS_FAIL;
                $msg = 'message：' . $e->getMessage() . '，line：' . $e->getLine();
                break;
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 版本更新
     * */
    public function versionUpdate()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            try {
                $this->I('id', '版本数据ID', 'int', true, '版本数据ID不能为空');
                $this->I('version_id', '版本号', 'string', false, '版本号不能为空');
                $this->I('platform_id', '平台', 'int', false, '平台不能为空');//  1:IOS 2:Android
                $this->I('upgrade_type', '升级类型', 'int', false, '升级类型不能为空');// 0.不升级 1. 强制升级 2.普通升级
                $this->I('channel_id', '渠道ID', 'int', false, '渠道ID不能为空');
                $this->I('download_url', '下载链接', 'string', false, '下载链接不能为空');
                $this->I('describe', '版本说明', 'string', false, '版本说明不能为空');
                $this->I('audit_switch', '开关', 'int', false);// 0:关闭 1:开启

                $variables = [];
                $checkParams = $this->check($this->requestData, $variables); //校验数据
                extract($checkParams);
                if ($code !== Hint::SUCCESS) {
                    break;
                }
                extract($variables); //数组参数化

                $id = $this->requestData['id'];
                // 移除请求数据中的ID
                unset($this->requestData['id']);

                if (empty($this->requestData)) {
                    $code = Hint::ERR_PARAMS_CHECK_FAIL;
                    $msg = Hint::getErrCodeMsg($code) . ':至少包含任意一个业务参数';
                    break;
                }

                $this->model_system->table = 'system_version';
                $ret = $this->model_system->singleUpdate(['id' => $id], $this->requestData);
                if (!$ret) {
                    $code = Hint::ERR_DATA_UPDATE_FAIL;
                    $msg = '版本' . Hint::getErrCodeMsg($code);
                    break;
                }

                $data['id'] = intval($id);

                $this->model_system->clear_cache(2);

            } catch (\Exception $e) {
                $code = Hint::ERR_SYS_FAIL;
                $msg = 'message：' . $e->getMessage() . '，line：' . $e->getLine();
                break;
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 版本删除
     * */
    public function versionRemove()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            try {
                $this->I('id', '版本数据ID', 'int', true, '版本数据ID不能为空');

                $variables = [];
                $checkParams = $this->check($this->requestData, $variables); //校验数据
                extract($checkParams);
                if ($code !== Hint::SUCCESS) {
                    break;
                }
                extract($variables); //数组参数化

                $this->model_system->table = 'system_version';
                $ret = $this->model_system->singleRemove($this->requestData);
                if (!$ret) {
                    $code = Hint::ERR_DATA_REMOVE_FAIL;
                    $msg = '版本' . Hint::getErrCodeMsg($code);
                    break;
                }

            } catch (\Exception $e) {
                $code = Hint::ERR_SYS_FAIL;
                $msg = 'message：' . $e->getMessage() . '，line：' . $e->getLine();
                break;
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    public function getCustomers($type) {
        return $this->model_system->getCustomer($type);
    }


    /**
     * 列表分页
     * */
    public function getHelpList()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            $page = $this->requestData['page'] ?? 0;
            $limit = $this->requestData['limit'] ?? 10;
            $appUa = $this->parse_app_UA();
            $app = $appUa["app"];
            $data = $this->helpModel->getHelpList([], $page, $limit, $app);

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 收集用户信息
     * */
    public function pushUserInfo()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            //获取用户信息
            $currentUser = $this->model_user->get_current_user();
            $data = $this->requestData ?? null;
            $userId = $data['user_id'] ? $data['user_id'] : $currentUser['user_id'];

            //更新device_token
            if (isset($data['device_token'])) {
                $this->model_user->setUserDeviceToken($userId, $data['device_token']);
            }

        } while (false);

        return compact('code', 'msg', 'data');
    }

    //设置渠道号指定跳转的房间
    public function setChannelRoomId()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];
        do {
            $this->I('channel_no', '渠道号', 'string', true, '渠道号不能为空');
            $this->I('room_id', '房间id', 'string', true, '房间id不能为空');//输入的是房间uid, 需要转换成房间id

            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }


            $channelArr = explode(',', $this->requestData['channel_no']);


            //room_id有可能传入多个
            $tempRoomUuids = [];
            $arr = explode(',', $this->requestData['room_id']);
            foreach ($arr as $item) {
                $item = trim($item);
                if ($item) {
                    $tempRoomUuids[] = $item;
                }
            }

            $roomIds = Room::query()->select(['room_id'])->whereIn('room_uid', $tempRoomUuids)->pluck('room_id')->toArray();
            foreach ($channelArr as $channel_id){
                $this->helpModel->setChannelRoomId($channel_id, implode(',', $roomIds));
            }
        }while(false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 获取渠道跳房间list
     *
     * @return array
     */
    public function getChannelRoomIdList()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];
        do{
            $data = $this->helpModel->getChannelRoomIdList();
        }while(false);
        return compact('code','msg', 'data');
    }

    /**
     * 删除渠道跳房间记录
     *
     * @return array
     */
    public function delChannelRoomDel()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];
        do {
            $this->I('channel_no', '渠道号', 'string', true, '渠道号不能为空');
            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }

            $this->helpModel->delChannelRoom($this->requestData['channel_no']);
        }while(false);
        return compact('code','msg', 'data');
    }

    /**
     * 根据渠道号获取指定跳转房间(v1版，暂停使用)
     *
     * @return array
     */
    public function getRoomIdByChannel()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        do {
            $res = $this->parse_app_UA();
            $data = ['room_id' => 0, 'type' => 0, 'pre' => '',];
            if (!empty($res['channel_id'])){
                $room_id = $this->helpModel->getRoomIdByChannel($res['channel_id']);
                if(!empty($room_id)){
                    //获取房间前缀
                    $data['pre'] = substr($room_id,0,strrpos($room_id,"_"));
                    if (($data['pre'] ?? '') && in_array($data['pre'],array_keys(Help::CHANNEL_ROOM_PRE_LIST))) {
                        $data['type'] = Help::CHANNEL_ROOM_PRE_LIST[$data['pre']] ?? 0;
                        $data['room_id'] = substr($room_id,-1,strlen($room_id) - strrpos($room_id,"_"));
                    }
                }

                //没有前缀的房间id=来来房间，需要判断是否开启
                if (!$data['pre']) {
                    //判断房间是否开启，开启返回房间id ,不开启返回0
                    if($this->model_room->get_opened($room_id)){
                        $data['room_id'] = $room_id;
                    }
                }
            }
        }while(false);
        return compact('code', 'msg', 'data');
    }

    /**
     * 根据渠道号获取指定跳转房间
     *
     * @return array
     */
    public function getRoomIdByChannelV2($requestData)
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = ['room_id' => 0, 'type' => 0, 'pre' => '',];
        if (!is_array($requestData) || !isset($requestData['user_id'])){
            return compact('code', 'msg', 'data');
        }

        $userRegisterLog = UserRegisterLog::query()->where('user_id', $requestData['user_id'])->limit(1)->get()->toArray();
        if (!$userRegisterLog || !isset($userRegisterLog[0]['platform'])) {
            return compact('code', 'msg', 'data');
        }

        $platform = $userRegisterLog[0]['platform'];
        $room_id = $this->helpModel->getRoomIdByChannel($platform);
        if (empty($room_id)) {
            return compact('code', 'msg', 'data');
        }

        $data['pre'] = substr($room_id,0, strrpos($room_id,"_"));//获取房间前缀
        if (($data['pre'] ?? '') && in_array($data['pre'],array_keys(Help::CHANNEL_ROOM_PRE_LIST))) {
            $data['type'] = Help::CHANNEL_ROOM_PRE_LIST[$data['pre']] ?? 0;
            $data['room_id'] = substr($room_id,-1,strlen($room_id) - strrpos($room_id,"_"));
        }

        //没有前缀的房间id=来来房间，需要判断是否开启
        if (!$data['pre']) {
            //判断房间是否是多个
            $roomIds = explode(',', $room_id);
            shuffle($roomIds);
            foreach ($roomIds as $rid){
                //判断房间是否开启，开启返回房间id ,不开启返回0
                if ($this->model_room->get_opened($rid)) {
                    $data['room_id'] = $rid;
                    break;
                }
            }
        }

        return compact('code', 'msg', 'data');
    }

    /**获取系统说明信息
     * @return array
     */
    public function getExplain(){
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            $this->I('type', 'type', 'int', false);
            $this->I('key', 'key值', 'string', false);
            $type = $this->requestData['type'] ?? 0;
            $key = $this->requestData['key'] ?? 'all';
            $data = $this->model_system->getExplain($type ,$key);

        } while (false);

        return compact('code', 'msg', 'data');
    }

    public function getNavMenuRes(){
        return $this->model_system->getNavMenuRes();
    }

    public function getRoomFastMsg(){
        return $this->model_system->getRoomFastMsg();
    }

    public function postAsaReport(array $data = []) {
        $paras = $data['paras'];
        $paras = json_decode($paras, true);
        $paras = array_values($paras);
        $paras = $paras[0] ?? [];

        $ua = $this->parse_app_UA();
        $guid = $ua['guid'] ?? '';
        $data['iad_purchase_date'] = $paras['iad-purchase-date'] ?? '';
        $data['iad_keyword'] = $paras['iad-keyword'] ?? '';
        $data['iad_adgroup_id'] = $paras['iad-adgroup-id'] ?? '';
        $data['iad_campaign_id'] = $paras['iad-campaign-id'] ?? '';
        $data['iad_lineitem_id'] = $paras['iad-lineitem-id'] ?? '';
        $data['iad_conversion_date'] = $paras['iad-conversion-date'] ?? '';
        $data['iad_org_id'] = $paras['iad-org-id'] ?? '';
        $data['iad_keyword_id'] = $paras['iad-keyword-id'] ?? '';
        $data['iad_conversion_type'] = $paras['iad-conversion-type'] ?? '';
        $data['iad_country_or_region'] = $paras['iad-country-or-region'] ?? '';
        $data['iad_org_name'] = $paras['iad-org-name'] ?? '';
        $data['iad_campaign_name'] = $paras['iad-campaign-name'] ?? '';
        $data['iad_click_date'] = $paras['iad-click-date'] ?? '';
        $data['iad_attribution'] = $paras['iad-attribution'] ?? '';
        $data['iad_adgroup_name'] = $paras['iad-adgroup-name'] ?? '';
        $data['iad_keyword_matchtype'] = $paras['iad-keyword-matchtype'] ?? '';
        $data['iad_lineitem_name'] = $paras['iad-lineitem-name'] ?? '';
        $data['guid'] = $guid;

        return $this->model_system->createAsaReport($data);
    }

    public function deviceRiskQueue(array $data = []) {
        $this->model_system->deviceRiskQueue($data);
    }

    public function deviceRisk() {
        $queue =$this->model_system->getDeviceRiskQueue();
        if(!$queue) {
            return;
        }
        $body = json_decode($queue, true);
        if(empty($body)) {
            return;
        }

        // 请求参数
        $userId = $body['user_id'];
        $deviceid = $body['deviceid'];
        $timestamp = $body['timestamp'];
        $ip = $body['ip'];
        $isPhoneExist = $body['is_phone_exiist'];
        $countryCode = $body['country_code'];
        $userAgent = $body['ua'];

        $userInfo = $this->model_user->getUserInfoByCondition(['user_id' => $userId], [ 'user_id', 'password', 'mobile_phone', 'nickname' ]);
        if(empty($userInfo)) {
            return;
        }

        $mobilePhone = $userInfo['mobile_phone'];
        if (isset($userInfo['mobile_phone']) && substr($userInfo['mobile_phone'] , 0 , 1) == 2) {
            $mobilePhone = '';
        }

        // 验证
        // $data = [
        //         'tokenId' => $this->model_user->generatedSmTokenId($userInfo['user_id']),
        //         'ip' => $ip,
        //         'timestamp' => $timestamp,
        //         'deviceId' => $deviceid,
        //         'hashPassword' => $userInfo['password'],
        //         'isPhoneExist' => $isPhoneExist,
        //         'phone' => $mobilePhone,
        //         'countryCode' => $countryCode,
        //         'os' => $userAgent['os_name'],
        //         'appVersion' => $userAgent['version_no'],
        //         'nickName' => $userInfo['nickname']
        // ];
        // $res = (new Shumei())->antiFraudCheck('register', $data);

        // 存储验证结果
        $this->model_user->insertDeviceRisk([
            'guid' => $userAgent['guid'] ?? 0,
            'device_id' => $deviceid,
            'version_no' => $userAgent['version_no'] ?? '',
            'os_name' => $userAgent['os_name'] ?? '',
            'phone' => $userInfo['mobile_phone'] ?? '',
            'risk_level' => $res['riskLevel'] ?? '',
            'score' => $res['score'] ?? 0,
            'detail' => json_encode($res['detail'] ?? []),
            'created_at' => date('Y-m-d H:i:s'),
            'type' => 1,
            'detail_json' => json_encode($res['detail'] ?? [])
        ]);
    }

    public function pushClick(){
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            $this->I('push_msg_id', 'pushID', 'int', true);

            $push_msg_id = $this->requestData['push_msg_id'];

            Redis::HINCRBY(sprintf($this->pushCheckHour,date('G')),$push_msg_id, 1);
        } while (false);

        return compact('code', 'msg', 'data');
    }

    public function getPushClickLog(){
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {

            $pushCheckHour = sprintf($this->pushCheckHour,date('G') - 1);
            $dataPrev = Redis::HGETALL($pushCheckHour);
            $lastHour = intval(date('G') - 1);
            if (date('G') - 1 < 0) $lastHour = 23;
            $data[$lastHour] = $dataPrev;
            $pushCheckHour = sprintf($this->pushCheckHour,date('G'));
            $dataThis = Redis::HGETALL($pushCheckHour);
            $data[date('G')] = $dataThis;

        } while (false);

        return compact('code', 'msg', 'data');
    }

    public function delPushClickLog(){
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            $lastHour = intval(date('G') - 1);
            if (date('G') - 1 < 0) $lastHour = 23;
            $pushCheckHour = sprintf($this->pushCheckHour,$lastHour);
            $data = Redis::DEL($pushCheckHour);
        } while (false);

        return compact('code', 'msg', 'data');


    }

    public function setNavMenu($key,$value){
        $navData = $this->model_system->findNavByKey($key);
        if ($navData) {
            return $this->model_system->updateNavMenu($navData['id'],['value' => $value]);
        }else{
            $navList = $this->model_system->navList();
            $navList = array_column($navList, null,'key');
            $data = [
                'key'           => $navList[$key]['key'],
                'desc'          => $navList[$key]['desc'],
                'value'         => $value,
            ];
            return $this->model_system->addNavMenu($data);
        }

    }

    public function setNavMenuRedis(){
        return $this->model_system->setNavMenuRedis();
    }

    public function delNavMenu($id){
        return $this->model_system->delNavMenu($id);
    }

    public function getHideRanking(){
        return $this->model_system->getHideRanking();
    }


    /**
     * 配置相关业务逻辑处理
     *
     * @param $key
     * @param $value
     * @return void
     */
    private function handleSystemConfigLogic($key, $value)
    {
        switch ($key) {
            case 'hide_ranking':
                $hide = $value > 0;
                (new MsgServices)->sendHideRanding($hide);
                break;
            case 'gray_filter_switch':
                (new MsgServices)->sendHideGrayFilter($value);
                break;
        }
    }

    //获取阿里云验证码配置
    public function getAliVerify(){
        $aliVerifyConfig = config("ali_verify");
        $result = [];
        $result['sceneId'] = $aliVerifyConfig['sceneId'];
        $result['prefix'] = $aliVerifyConfig['prefix'];
        $result['requestUrl'] = env('ACTIVITY_URL').'/captcha';
        $result['status'] = 0;//状态 0=未启用 1=启用

        return $result;
    }

    //阿里云验证码校验
    public function aliVerify($captchaVerifyParam, $phone){
        do{
            $data = [
                'code' => Hint::SUCCESS,
                'data' => [],
                'msg' => '成功'
            ];
            if(empty($phone)){
                $data = [
                    'code' => Hint::ERR_NORMAL,
                    'data' => [],
                    'msg' => '系统检测到您的版本过低,请升级到最新版本'
                ];
                break;
            }
            $result = $this->aliVerifyModel->verifyIntelligentCaptcha($captchaVerifyParam);      
            if($result == true) {
                $smsToken = md5($phone);
                $data = [
                    'code' => Hint::SUCCESS,
                    'data' => ['sms_token'=>$smsToken],
                    'msg' => '成功'
                ];
                Redis::SET('ALI:VERIFY:TOKEN:'.$phone,$smsToken);
                Redis::EXPIRE('ALI:VERIFY:TOKEN:'.$phone,65);//1分钟有效期
            }else{
                $data = [
                    'code' => Hint::CHECK_CAPTCHA_CODE_ERROR,
                    'data' => [],
                    'msg' => '图形验证码错误'
                ];
            }
        }while(false);
        return $data;
    }

    /**
     * 添加黑名单语言
     */
    public function addBlackWord($params=[]){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            $id = $this->userBlacklistModel->addBlackWord($params);

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 编辑黑名单语言
     */
    public function editBlackWord($id, $params=[]){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if(empty($id) || empty($params)) {
                break;
            }
            $res = $this->userBlacklistModel->editBlackWord($id, $params);

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 删除黑名单语言
     */
    public function delBlackWord($id, $params=[]){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if(empty($id) || empty($params)) {
                break;
            }
            $params['is_delete'] = 1;
            $res = $this->userBlacklistModel->editBlackWord($id, $params);

        } while (false);

        return compact('code', 'msg', 'data');
    }

}
